<template>
  <div class="box">
    <div>
      头部图标
    </div>
    <div class="login_title">
      商城系统登录
    </div>
    <div class="err" v-show="err"><span>登录失败, 该用户不存在或已删除</span></div>
    <div>
      <el-form
          :model="userValidateForm"
          ref="formRef">
        <el-form-item
            prop="account"
            :rules="[
        { required: true, message: '账号不能为空' ,trigger:'blur'},
      ]"
            style="width: 100%">

          <el-input
              v-model="userValidateForm.account"
              class="userInput"
              placeholder="请输入用户名"
              :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item
            prop="password"
            :rules="[
        { required: true, message: '密码不能为空' ,trigger:'blur'},
      ]"
        >
          <el-input
              v-model="userValidateForm.password"
              type="password"
              class="userInput"
              placeholder="请输入密码"
              :prefix-icon="Lock"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" style="width: 100%;margin-top: 30px;height: 40px" @click="toLogin(formRef)">确定</el-button>
  </div>
</template>
<script setup>
import {User, Lock} from '@element-plus/icons-vue'
import {ref, reactive} from 'vue'
import {login} from "../../../HTTP/api";
import { ElMessage } from 'element-plus'
import{useRouter} from 'vue-router'
const router=useRouter()
//表单
const formRef = ref()
//验证字段名
const userValidateForm = reactive({
  account: '',
  password: ''
})
//错误框
let err=ref(false)
//登录
const toLogin = (formRef) => {
  formRef.validate((valid) => {
    if (valid) {
        login({
          name:userValidateForm.account,
          pw:userValidateForm.password
        }).then(res=>{
          console.log(res)
          if(res.code===2000){
            ElMessage({
              message: '登录成功',
              type: 'success',
            })
            sessionStorage.setItem("userToken",res.data.token)
            err.value=false
           setTimeout(()=>{
             router.push({path:'/admin'})
           },1000)
          }
          if(res.code===2010){
            ElMessage.error('账号或者密码错误')
            err.value=true

          }
        }).catch(reason=>{
          ElMessage.error(reason)
          sessionStorage.clear()
        })
    } else {
      return false
    }
  })
}
</script>
<style scoped>
.box {
  width: 340px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login_title {
  font-size: 20px;
  color: #6c7293;
  font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;
  margin: 20px 0;
}

.userInput {
  margin: 10px 0;
  height: 40px;
  width: 340px;
}
.err{
  font-size: 14px;
  line-height: 40px;
  height: 40px;
  width: 100%;
  border: 1px solid red;
  color: rgba(0,0,0,.85);
}
.err span{
    margin-left: 20px;
}
</style>
